package bdhub.littletail.app;

import android.app.Application;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.core.ImagePipelineConfig;

import bdhub.littletail.lib.database.DatabaseMigration;
import bdhub.littletail.lib.utils.log.CLog;
import se.emilsjolander.sprinkles.Sprinkles;

/**
 * Created by FreddyChen on 16/2/22.
 * chenshichao@outlook.com
 */
public class LittleTailApplication extends Application {

    private static final String TAG = LittleTailApplication.class.getSimpleName();

    private static LittleTailApplication instance;

    public static LittleTailApplication sharedInstance() {
        if(null == instance) {
            throw new IllegalStateException("not init...");
        }

        return instance;
    }
    /**
     * 程序主入口
     */
    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;

        initFresco();
    }

    /**
     * 根据用户id初始化数据库（一个用户对于一个数据库文件），创建所需的表
     * 这个方法需要synchronized
     * @param id
     *              用户id
     */
    public synchronized void initDatabase(long id) {
        // 如果以前还有数据库连接打开中，先释放掉
        Sprinkles.release();
        CLog.v(TAG, "initDatabase is started...");
        Sprinkles sprinkles = Sprinkles.init(sharedInstance(), id + ".db", DatabaseMigration.VERSION);
        sprinkles.addMigration(new DatabaseMigration());
        CLog.v(TAG, "initDatabase is finished...");
    }

    private void initFresco() {
        ImagePipelineConfig config = ImagePipelineConfig.newBuilder(this)
                //                .setBitmapMemoryCacheParamsSupplier(bitmapCacheParamsSupplier)
                //                .setCacheKeyFactory(cacheKeyFactory)
                //                .setDownsampleEnabled(true)
                //                .setEncodedMemoryCacheParamsSupplier(encodedCacheParamsSupplier)
                //                .setExecutorSupplier(executorSupplier)
                //                .setImageCacheStatsTracker(imageCacheStatsTracker)
                //                .setMainDiskCacheConfig(mainDiskCacheConfig)
                //                .setMemoryTrimmableRegistry(memoryTrimmableRegistry)
                //                .setNetworkFetchProducer(networkFetchProducer)
                //                .setPoolFactory(poolFactory)
                //                .setProgressiveJpegConfig(progressiveJpegConfig)
                //                .setRequestListeners(requestListeners)
                //                .setSmallImageDiskCacheConfig(smallImageDiskCacheConfig)
                .build();
        Fresco.initialize(this, config);
    }
}
